package com.tlw.practice.tlw.utils;

    import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.impl.ClaimsHolder;
import com.auth0.jwt.interfaces.DecodedJWT;
    import com.tlw.practice.tlw.common.CommonResult;
    import com.tlw.practice.tlw.common.ResultCode;
    import com.tlw.practice.tlw.exception.BusinessException;
    import com.tlw.practice.tlw.pojo.form.UserLoginForm;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.security.core.userdetails.UserDetails;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    /**
     * 盐值
     */
    private static final String SIGN="LIUYISHOU@Token666";


    /**
     * 生成令牌
     * @param map payload载荷声明参数
     * @return
     */
    public  static String getToken(Map<String,Object> map){
        //获取日历对象
        Calendar calendar=Calendar.getInstance();
        //默认7天过期
        calendar.add(Calendar.SECOND, 1000);
        //新建一个JWT的Builder对象
        JWTCreator.Builder builder = JWT.create();
        //将map集合中的数据设置进payload
        map.forEach((k,v)->{
            builder.withClaim(k, v.toString());
        });
        //设置过期时间和签名
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SIGN));

        return token;
    }

    /**
     * 生成令牌
     * @return
     */
    public  static String getToken(){
        //获取日历对象
        Calendar calendar=Calendar.getInstance();
        //默认7天过期
        calendar.add(Calendar.DATE, 7);
        //新建一个JWT的Builder对象
        JWTCreator.Builder builder = JWT.create();
        //设置过期时间和签名
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SIGN));

        return token;
    }

    /**
     * 验签并返回DecodedJWT
     * @param token  令牌
     */
    public  static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 根据用户信息生成token
     */
    public static String generateToken(UserLoginForm user) {
        Map<String, Object> claims = new HashMap<>(1);
        claims.put("username", user.getUsername());
        return getToken(claims);
    }

    /**
     * 从token中获取用户名
     */
    public static String getUserNameFromToken(String token) {
        String username;
        try {
            // 验证解签
            DecodedJWT verify = verify(token);
            // 取出用户名
            username = verify.getClaim("username").asString();
        } catch (Exception e) {
            e.printStackTrace();
            username = null;
            throw new BusinessException(CommonResult.error(ResultCode.UNABLE_GET_FROM_TOKEN));
        }
        return username;
    }

}